<?php
/**
 * List of user
 */

use Fox\Common\Customer;
use Fox\Generator;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Type;
use Custom\Control;
use Fox\Html\Screen;

$xview = Xview::instance();
$force = $xview->val("force");

$screen = new Screen("eControl","vlook");
$block = new Fox\Html\Block("bControl","Mois &agrave; Controler");
$block->add(new Fox\Html\Input("date",true,time()));
$screen->add($block);
if($screen->submitted() || $force)
{
	$inputs = $screen->get();
	if(!$screen->errors())
	{
		$data = array();
		// Load All Agency
		$finder = new Customer();
		$agencies = $finder->find(new Fox\Dao\SqlFragment("type = ?",array(Customer::TYPE_OFFICE)));
		foreach($agencies as $agency)
		{
			$agenceName[$agency->getId()] = $agency->name1;
		}

		$profiles = Fox\Authorization\Profile::findByAuthorizationName(User::AUTH_TO_BE_CTRL);
		foreach($profiles as $profil)
		{
			$profileId[] = $profil->proid;
		}
		$filters[] = new Fox\Dao\SqlFragment("w.proid IN (?)",array($profileId),array(Connection::PARAM_STR_ARRAY));
		$users = $xview->application()
						->users($filters);
		foreach($users as $user)
		{
			$detail = $user->getData();
			$detail['idusr'] = $user->idusr;
			$detail['op_entity'] = null;
			$agenciesId = $user->getPrefs('op_entity',true);
			if(!empty($agenciesId))
			{
				foreach($agenciesId as $id)
				{
					$detail['op_entity'] .= $agenceName[$id]."<br>";
				}

			}
			$detail['cdate'] = null;
			$data[$user->getId()] = $detail;
		}
		$query = \Fox\Dao::infos(Control::className())->handle()->createQueryBuilder();
		$query->select('uname','date','cdate')
				->from('controls','c');

		$date = new DateTime($inputs['date']);
		$date = new DateTime($date->format("Y-m-")."01");
		$fragments[] = new Fox\Dao\SqlFragment("( date = ? )",array($date),array(Type::DATE));
		$fragment = Fox\Dao\SqlFragment::combine($fragments);
		$result = $fragment->pushIn($query)->execute()->fetchAll(\PDO::FETCH_ASSOC);
		foreach($result as $detail)
		{
			if(isset($data[$detail['uname']]))
				$data[$detail['uname']]['cdate'] = $detail['cdate'];
		}

		$grid = new Fox\Grid("gControl");
		$grid->fieldcat(array('fname','lname','op_entity',array('validatedon','cdate')));
		$grid->fieldcat()->behaviors(Fox\Behaviors::key(Fox\Generator::useElement("idusr")));
		$grid->setCoche();
		$grid->setDatas($data);
		$dateString = $date->format("Y-m-d");
		//(idgrid,targetUrl,umark,emode,callback,fader)
		$callback = "Refresh(\'?mod=inquiry&act=month&sac=agency&force=true&date=$dateString\');";
		$grid->footer()->add(new Fox\Html\Button('dunning',
										"GridLinesAction('gControl','?mod=controlling&act=dunning&date=$dateString','X','S','$callback');"
										,"Relancer"));

	}
}
echo $screen->display();
if(isset($grid))
	echo $grid->display();